package com.ifast.car.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.ifast.car.domain.CarInfoDO;
import com.ifast.car.domain.CarPositionDO;
import com.ifast.car.service.CarInfoService;
import com.ifast.car.service.CarPositionService;
import com.ifast.common.type.EnumErrorCode;
import com.ifast.common.utils.DateUtil;
import com.ifast.common.utils.DateUtils;
import com.ifast.common.utils.ImportExcelUtil;
import com.ifast.common.utils.Result;
import com.ifast.common.utils.StringUtils;

/**
 * 
 * <pre>
 * 车辆信息
 * </pre>
 * 
 * <small> 2018-04-11 15:15:58 | Aron</small>
 */
@Controller
@RequestMapping("/car/carInfo")
public class CarInfoController {
	@Autowired
	private CarInfoService carInfoService;

	@Autowired
	private CarPositionService carPositionService;

	@GetMapping()
	@RequiresPermissions("car:carInfo:carInfo")
	String CarInfo() {
		return "car/carInfo/carInfo";
	}

	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("car:carInfo:carInfo")
	public Result<Page<CarInfoDO>> list(Integer pageNumber, Integer pageSize, CarInfoDO carInfoDTO) {
		// 查询列表数据
		Page<CarInfoDO> page = new Page<>(pageNumber, pageSize);

		Wrapper<CarInfoDO> wrapper = new EntityWrapper<CarInfoDO>(carInfoDTO);
		
		wrapper.like("mobile", carInfoDTO.getMobile());
		carInfoDTO.setMobile("");
		wrapper.like("plate_number", carInfoDTO.getPlateNumber());
		carInfoDTO.setPlateNumber("");
		//wrapper.where("mobile like '%{0}%'", carInfoDTO.getMobile());
		page = carInfoService.selectPage(page, wrapper);
		int total = carInfoService.selectCount(wrapper);
		page.setTotal(total);
		return Result.ok(page);
	}

	@GetMapping("/add")
	@RequiresPermissions("car:carInfo:add")
	String add() {
		return "car/carInfo/add";
	}

	@GetMapping("/edit/{cid}")
	@RequiresPermissions("car:carInfo:edit")
	String edit(@PathVariable("cid") Long cid, Model model) {
		CarInfoDO carInfo = carInfoService.selectById(cid);
		model.addAttribute("carInfo", carInfo);
		model.addAttribute("contractTime", DateUtils.format(carInfo.getContractTime(), DateUtils.DATE_TIME_PATTERN_19));
		return "car/carInfo/edit";
	}

	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("car:carInfo:add")
	public Result<String> save(CarInfoDO carInfo) {
		carInfo.setCid(carInfoService.getId() + 1);
		if (carInfoService.insert(carInfo)) {
			CarPositionDO carPosition = new CarPositionDO();
			carPosition.setPositionid(carInfo.getCid());
			carPosition.setCid(carInfo.getCid());
			List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
			HashMap<String, Object> hm = new HashMap<String, Object>();
			hm.put("time", carInfo.getContractTime());
			hm.put("data", "签署运输合同");
			list.add(hm);
			carPosition.setNewPosition(
					JSON.toJSONStringWithDateFormat(list, "yyyy-MM-dd", SerializerFeature.WriteDateUseDateFormat));
			carPositionService.insert(carPosition);

			return Result.ok();
		}
		return Result.fail();
	}

	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("car:carInfo:edit")
	public Result<String> update(CarInfoDO carInfo) {
		carInfoService.updateAllColumnById(carInfo);
		return Result.ok();
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ResponseBody
	@RequiresPermissions("car:carInfo:remove")
	public Result<String> remove(Long cid) {
		if (carInfoService.deleteById(cid)&&carPositionService.deleteById(cid)) {
			return Result.ok();
		}
		return Result.fail();
	}

	/**
	 * 删除
	 */
	@PostMapping("/batchRemove")
	@ResponseBody
	@RequiresPermissions("car:carInfo:batchRemove")
	public Result<String> remove(@RequestParam("ids[]") Long[] cids) {
		carInfoService.deleteBatchIds(Arrays.asList(cids));
		return Result.ok();
	}

	@GetMapping("/batchImport")
	@RequiresPermissions("car:carInfo:batchImport")
	String batchImport() {
		return "car/carInfo/batchImport";
	}

	@ResponseBody
	@PostMapping("/uploadExcel")
	public Result<String> uploadExcel(@RequestParam("file") MultipartFile file) {
		try {
			List<List<Object>> list = new ImportExcelUtil().getBankListByExcel(file.getInputStream(),
					file.getOriginalFilename(), 1);
			for (int i = 0; i < list.size(); i++) {
				CarInfoDO carData = carInfoService.selectById(StringUtils.isNull(list.get(i).size()>=1?list.get(i).get(0) + "":""));
				if (carData != null) {
					// carData.setCid(Long.valueOf(list.get(i).get(0)+""));
					carData.setMobile(StringUtils.isNull(list.get(i).size()>=2?list.get(i).get(1) + "":""));
					carData.setPlateNumber(StringUtils.isNull(list.get(i).size()>=3?list.get(i).get(2) + "":""));
					carData.setModel(StringUtils.isNull(list.get(i).size()>=4?list.get(i).get(3) + "":""));
					carData.setDeparture(StringUtils.isNull(list.get(i).size()>=5?list.get(i).get(4) + "":""));
					carData.setDestination(StringUtils.isNull(list.get(i).size()>=6?list.get(i).get(5) + "":""));
					carData.setInsurer(StringUtils.isNull(list.get(i).size()>=7?list.get(i).get(6) + "":""));
					carData.setInsurerMobile(StringUtils.isNull(list.get(i).size()>=8?list.get(i).get(7) + "":""));
					carData.setInsurerWebsite(StringUtils.isNull(list.get(i).size()>=9?list.get(i).get(8) + "":""));
					carData.setPolicyNumber(StringUtils.isNull(list.get(i).size()>=10?list.get(i).get(9) + "":""));
					carData.setContractTime(DateUtil.strToDate(StringUtils.isNull(list.get(i).size()>=11?list.get(i).get(10) + "":"")));
					carInfoService.updateAllColumnById(carData);
				} else {
					carData = new CarInfoDO();
					carData.setCid(Long.valueOf(StringUtils.isNull(list.get(i).size()>=1?list.get(i).get(0) + "":"")));
					carData.setMobile(StringUtils.isNull(list.get(i).size()>=2?list.get(i).get(1) + "":""));
					carData.setPlateNumber(StringUtils.isNull(list.get(i).size()>=3?list.get(i).get(2) + "":""));
					carData.setModel(StringUtils.isNull(list.get(i).size()>=4?list.get(i).get(3) + "":""));
					carData.setDeparture(StringUtils.isNull(list.get(i).size()>=5?list.get(i).get(4) + "":""));
					carData.setDestination(StringUtils.isNull(list.get(i).size()>=6?list.get(i).get(5) + "":""));
					carData.setInsurer(StringUtils.isNull(list.get(i).size()>=7?list.get(i).get(6) + "":""));
					carData.setInsurerMobile(StringUtils.isNull(list.get(i).size()>=8?list.get(i).get(7) + "":""));
					carData.setInsurerWebsite(StringUtils.isNull(list.get(i).size()>=9?list.get(i).get(8) + "":""));
					carData.setPolicyNumber(StringUtils.isNull(list.get(i).size()>=10?list.get(i).get(9) + "":""));
					carData.setContractTime(DateUtil.strToDate(StringUtils.isNull(list.get(i).size()>=11?list.get(i).get(10) + "":"")));
					carInfoService.insert(carData);

					CarPositionDO carPosition = new CarPositionDO();
					carPosition.setPositionid(carData.getCid());
					carPosition.setCid(carData.getCid());
					List<HashMap<String, Object>> newlist = new ArrayList<HashMap<String, Object>>();
					HashMap<String, Object> hm = new HashMap<String, Object>();
					hm.put("time", carData.getContractTime());
					hm.put("data", "签署运输合同");
					newlist.add(hm);
					carPosition.setNewPosition(JSON.toJSONStringWithDateFormat(newlist, "yyyy-MM-dd",
							SerializerFeature.WriteDateUseDateFormat));
					carPositionService.insert(carPosition);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return Result.build(EnumErrorCode.FileUploadGetBytesError.getCode(),
					EnumErrorCode.FileUploadGetBytesError.getMsg());
		}
		return Result.ok();
	}

	@ResponseBody
	@GetMapping("/api/v1/getCarInfo")
	public Result<List<CarInfoDO>> getCarInfo(String mobile) {
		List<CarInfoDO> carData = carInfoService.getCarInfoByMoblie(mobile);
		if (carData != null) {
			return Result.ok(carData);
		}
		return Result.ok();
	}

	@ResponseBody
	@GetMapping("/api/v1/getCarInfo2")
	public JSONPObject getCarInfo(String jsonpCallback, String mobile) {
		/*CarInfoDO carData = carInfoService.getCarInfoByMoblie(mobile);
		MappingJacksonValue mappingJacksonValue = null;
		if (carData != null) {
			mappingJacksonValue = new MappingJacksonValue(Result.ok(carData));
		}else {
			mappingJacksonValue = new MappingJacksonValue(Result.ok());
		}
	    mappingJacksonValue.setJsonpFunction(jsonpCallback);
	    return mappingJacksonValue;*/
		
		List<CarInfoDO> carData = carInfoService.getCarInfoByMoblie(mobile);
		if (carData != null) {
			return new JSONPObject(jsonpCallback, Result.ok(carData));
		}
		return new JSONPObject(jsonpCallback, Result.ok());
	}

}
